from flask import Flask, request, jsonify, send_from_directory, render_template
import os
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from datetime import datetime

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/resume_images'

# 确保上传文件夹存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/crawl-resume', methods=['GET'])
def crawl_resume():
    url = request.args.get('url')
    if not url:
        return jsonify({"error": "URL参数缺失"}), 400
    
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept-Language': 'zh-CN,zh;q=0.9'
        }
        
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        
        # 编码处理
        encodings_to_try = ['utf-8', 'gbk', 'gb2312', 'big5', 'iso-8859-1']
        decoded_text = None
        
        for encoding in encodings_to_try:
            try:
                decoded_text = response.content.decode(encoding)
                if '的' in decoded_text or '是' in decoded_text or '我' in decoded_text:
                    break
            except UnicodeDecodeError:
                continue
        
        if decoded_text is None:
            decoded_text = response.text

        soup = BeautifulSoup(decoded_text, 'html.parser')
        
        resume_data = {
            "basic_info": {},
            "sections": [],
            "images": []
        }
        
        # 提取基本信息
        header = soup.find('header')
        if header:
            name = header.find('h1').get_text().strip() if header.find('h1') else "未提供姓名"
            resume_data['basic_info']['name'] = name
            resume_data['basic_info']['job_intention'] = header.find('p').get_text().strip() if header.find('p') else "未提供求职意向"
            
            contact_info = header.find('div', class_='contact-info')
            if contact_info:
                resume_data['basic_info']['contact'] = {
                    'phone': None,
                    'email': None,
                    'github': None
                }
                for item in contact_info.find_all('p'):
                    text = item.get_text().strip()
                    if '电话' in text or '手机' in text:
                        resume_data['basic_info']['contact']['phone'] = text.split(':')[-1].strip()
                    elif '邮箱' in text or '邮件' in text:
                        resume_data['basic_info']['contact']['email'] = text.split(':')[-1].strip()
                
                github_link = contact_info.find('a')
                if github_link:
                    resume_data['basic_info']['contact']['github'] = github_link['href']
        
        # 提取详细简历信息
        sections = soup.find_all('section', class_='section')
        for section in sections:
            section_title = section.find('h2').get_text().strip() if section.find('h2') else "无标题"
            section_data = {
                "title": section_title,
                "content": []
            }
            
            content = section.find('div', class_='content')
            if content:
                if section_title == "技能专长":
                    section_data['content'] = [li.get_text().strip() for li in content.find_all('li')]
                else:
                    paragraphs = [p.get_text().strip() for p in content.find_all('p') if p.get_text().strip()]
                    section_data['content'] = paragraphs if paragraphs else [content.get_text().strip()]
            
            resume_data['sections'].append(section_data)
        
        # 下载个人照片
        profile_img = soup.find('img', class_='profile-img')
        if profile_img:
            img_url = profile_img.get('src')
            img_url = urljoin(url, img_url)
            img_filename = f"profile_{name.replace(' ', '_')}.jpg"
            img_path = os.path.join(app.config['UPLOAD_FOLDER'], img_filename)
            
            try:
                img_data = requests.get(img_url, headers=headers, timeout=5).content
                with open(img_path, 'wb') as f:
                    f.write(img_data)
                resume_data['images'].append({
                    "type": "profile",
                    "filename": img_filename,
                    "url": img_url
                })
            except Exception as e:
                resume_data['images'].append({
                    "type": "profile",
                    "filename": None,
                    "url": img_url,
                    "error": str(e)
                })
        
        return jsonify(resume_data)
    
    except requests.exceptions.RequestException as e:
        return jsonify({"error": f"请求失败: {str(e)}"}), 500
    except Exception as e:
        return jsonify({"error": f"发生错误: {str(e)}"}), 500

# 添加图片访问路由
@app.route('/get-image/<filename>')
def get_image(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    app.run(debug=True)